package com.ssy.lingxi.system.service.impl;

import com.ssy.lingxi.common.model.vo.PageVO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.system.dao.ContractParamRepository;
import com.ssy.lingxi.system.dto.request.ContractParamStateRequest;
import com.ssy.lingxi.system.entity.ContractParam;
import com.ssy.lingxi.system.service.IContractParamService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

/**
 * 电子合同参数配置服务实现类
 * @author yzc
 * @version 2.0.0
 * @date 2020/8/20
 */
@Service
public class ContractParamServiceImpl implements IContractParamService {

    @Resource
    private ContractParamRepository contractParamRepository;

    @Override
    public Wrapper<PageData<ContractParam>> pageContractParam(PageVO request) {
        Pageable page = PageRequest.of(request.getCurrent() - 1, request.getPageSize(), Sort.by("id").ascending());
        Page<ContractParam> pageList = contractParamRepository.findAll(page);

        return Wrapper.success(new PageData<>(pageList.getTotalElements(), pageList.getContent()));
    }

    @Transactional
    @Override
    public Wrapper updateStateContractParam(ContractParamStateRequest request) {
        ContractParam contractParam = contractParamRepository.findById(request.getId()).orElse(null);
        if (ObjectUtils.isEmpty(contractParam)) {
            return Wrapper.fail(ResponseCode.SYSTEM_RECORDS_DON_T_EXIST);
        }

        contractParam.setState(request.getState());
        contractParamRepository.saveAndFlush(contractParam);

        return Wrapper.success();
    }
}